package io.esirong.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

/**
 * 数量选择控件<></>
 * 简单选择数量加1 减一（+1-1）的功能，用于购物选择
 * Created by cy on 2017/4/28.
 */

public class NumberAddSubView extends LinearLayout implements View.OnClickListener, TextWatcher {

    private int maxValue;

    private int minValue;

    private int value;

    private TextView mBtnAdd;

    private TextView mBtnSub;

    private TextView mEtNum;

    private long lastClickTime;
    private OnNumberChangeListener mListener;
    private IAddSubCallback mCallBack;

    public NumberAddSubView(Context context) {
        this(context, null);
    }

    public NumberAddSubView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NumberAddSubView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化布局
        initView(context);
        //读取自定义属性的值并且设置
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NumberAddSubView, defStyleAttr, 0);
        if (a == null) {
            return;
        }
        try {
            value = a.getInt(R.styleable.NumberAddSubView_numValue, 1);
            maxValue = a.getInt(R.styleable.NumberAddSubView_maxNumValue, Integer.MAX_VALUE);
            minValue = a.getInt(R.styleable.NumberAddSubView_minNumValue, 1);
            Drawable btnBg = a.getDrawable(R.styleable.NumberAddSubView_btnDrawable);
            if (btnBg != null) {
                mBtnAdd.setBackgroundDrawable(btnBg);
                mBtnSub.setBackgroundDrawable(btnBg);
            }
        } finally {
            a.recycle();
        }

        setValue(value);

        updateBtn(value);
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.view_layout_number_add_sub, this, true);
        mBtnAdd = view.findViewById(R.id.btn_add);
        mBtnSub = view.findViewById(R.id.btn_sub);
        mEtNum = view.findViewById(R.id.et_num);

        mBtnAdd.setOnClickListener(this);
        mBtnSub.setOnClickListener(this);
        mEtNum.addTextChangedListener(this);
    }

    public void setOnNumberChangeListener(OnNumberChangeListener listener) {
        this.mListener = listener;
    }

    /**
     * 更新按键的状态，当量超出限制数时，按钮不可用
     *
     * @param count 数量
     */
    private void updateBtn(int count) {
        if (count > minValue) {
            setSubClickable(true);
        } else {
            setSubClickable(false);
        }
        if (count < maxValue) {
            setAddClickable(true);
        } else {
            setAddClickable(false);
        }
    }

    /**
     * 设置“增加”按钮是不是可以操作点击
     *
     * @param enable 是不是可以操作
     */
    public void setAddClickable(boolean enable) {
        if (enable) {
            mBtnAdd.setClickable(true);
            mBtnAdd.setTextColor(ContextCompat.getColor(getContext(), R.color.common_color_666666));
        } else {
            mBtnAdd.setTextColor(ContextCompat.getColor(getContext(), R.color.common_color_999999));
            mBtnAdd.setClickable(false);
        }
    }

    /**
     * 设置“减少”按钮是不是可以操作点击
     *
     * @param enable 是不是可以操作
     */
    public void setSubClickable(boolean enable) {
        if (enable) {
            mBtnSub.setClickable(true);
            mBtnSub.setTextColor(ContextCompat.getColor(getContext(), R.color.common_color_666666));
        } else {
            mBtnSub.setTextColor(ContextCompat.getColor(getContext(), R.color.common_color_999999));
            mBtnSub.setClickable(false);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_add) {
            if (isFastDoubleClick()) {
                return;
            }
            valueAdd();
            if (mCallBack != null) {
                mCallBack.onNumberChange(v);
            }

        } else if (id == R.id.btn_sub) {
            if (isFastDoubleClick()) {
                return;
            }
            valueSub();
            if (mCallBack != null) {
                mCallBack.onNumberChange(v);
            }

        }
    }

    /**
     * 用于连续快速点击按钮，短时间内不能连续切换
     */
    public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 300) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 数值递增
     */
    public void valueAdd() {
        if (!TextUtils.isEmpty(mEtNum.getText())) {
            int val = Integer.parseInt(mEtNum.getText().toString());
            if (mListener != null) {
                mListener.beforeChange(val + 1, val);
            }
            if (val < maxValue) {
                val++;
            }
            setValue(val);
        }
    }

    /**
     * 数值递减
     */
    public void valueSub() {
        if (!TextUtils.isEmpty(mEtNum.getText())) {
            int val = Integer.parseInt(mEtNum.getText().toString());
            if (mListener != null) {
                mListener.beforeChange(val - 1, val);
            }
            if (val > minValue) {
                val--;
            }
            setValue(val);
        }
    }

    public int getMaxValue() {
        return maxValue;
    }

    public void setMaxValue(int maxValue) {
        this.maxValue = maxValue;
    }

    public int getMinValue() {
        return minValue;
    }

    public void setMinValue(int minValue) {
        this.minValue = minValue;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
        mEtNum.setText(String.valueOf(value));
    }

    public void setRange(int minValue, int maxValue) {
        this.minValue = minValue;
        this.maxValue = maxValue;
    }

    public void setAddSubCallback(IAddSubCallback callBack) {
        this.mCallBack = callBack;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mListener != null) {
            if (!TextUtils.isEmpty(s)) {
                int val = Integer.parseInt(s.toString());
                updateBtn(val);
                if (val <= maxValue && val >= minValue) {
                    mListener.onChange(val, true);
                } else {
                    mListener.onChange(val, false);
                }
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    /**
     * 数字变化的监听
     */
    public interface OnNumberChangeListener {

        /**
         * 当数量变化了
         *
         * @param value     数量变化后的值
         * @param isInRange true：数量在限定范围内，false：数量不在限定范围内
         */
        void onChange(int value, boolean isInRange);

        /**
         * 改变之前回调
         *
         * @param destValue   修改后的值
         * @param originValue 修改前的值
         */
        void beforeChange(int destValue, int originValue);
    }

    public interface IAddSubCallback {

        void onNumberChange(View view);
    }
}
